<template>
  <span>
    <el-upload
      ref="upload"
      :auto-upload="false"
      :on-change="attachmentHandleOnChange"
      :show-file-list="false"
      :limit="1"
      :multiple="false"
      action="#"
      accept=""
      style="float:right;"
    >
      <el-button type="primary" size="mini" style="float:right;margin-bottom:5px;margin-left:0px;" icon="el-icon-paperclip" round>上传附件</el-button>
    </el-upload>
  </span>
</template>
<script>
import { batchUpdateFilePath } from '@/api/active-item'
import { uploadFile } from '@/api/change-item'
import { Message } from 'element-ui'
export default {
  props: {
    parent: {
      type: Object,
      default: null
    }
  },
  methods: {
    // 文件变动的钩子-附件上传
    attachmentHandleOnChange(file, fileList) {
      if (this.parent.ids.length < 1) {
        Message({
          message: '请选择需要上传附件的item。',
          type: 'error',
          duration: 3 * 1000
        })
        return
      }
      var size = file.size / 1024 / 1024
      if (size > 5) {
        Message({
          message: '文件大小必须小于5M。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
        return
      }
      this.$confirm('附件上传会覆盖原有附件，是否上传？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.parent.loading = true
        var formData = new FormData()
        formData.append('file', file.raw)
        uploadFile(formData).then(res => {
          if (res) {
            const filePath = res[0].fileUrl
            if (filePath) {
              batchUpdateFilePath({ ids: this.parent.ids, filePath: filePath }).then(() => {
                this.parent.toQuery()
                Message({
                  message: '上传成功。',
                  type: 'success',
                  duration: 3 * 1000
                })
                this.parent.loading = false
              }, error => {
                console.log(error)
                this.parent.loading = false
              })
            }
          }
        }, error => {
          console.log(error)
          this.parent.loading = false
        })
        fileList.pop()
      })
    }
  }
}
</script>

